package com.xd.core.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xd.common.constant.SysConstant;
import com.xd.common.exception.XkdException;
import com.xd.core.company.entity.Company;
import com.xd.core.company.entity.CompanyAccount;
import com.xd.core.company.mapper.CompanyAccountMapper;
import com.xd.core.note.ICacheService;
import com.xd.core.system.entity.*;
import com.xd.core.system.mapper.SysPermissionMapper;
import com.xd.core.system.mapper.SysRoleMapper;
import com.xd.core.system.mapper.UserGroupMapper;
import com.xd.core.company.service.ICompanyService;
import com.xd.core.system.service.ISysUserService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author : k
 * @Date : 2022/3/23
 * @Desc :
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private ISysUserService iSysUserService;
    @Resource
    private SysPermissionMapper sysPermissionMapper;
    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private ICompanyService companyService;
    @Resource
    private UserGroupMapper userGroupMapper;
    @Resource
    private CompanyAccountMapper companyAccountMapper;
    @Resource
    private ICacheService iCacheService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    //实现UserDetailsService接口，重写UserDetails方法，自定义用户的信息从数据中查询
    @Override
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException {

        //（认证，即校验该用户是否存在）查询用户信息
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getPhone, phone);
        SysUser user = iSysUserService.getOne(queryWrapper);
        //如果没有查询到用户
        if (Objects.isNull(user)) {
            throw new XkdException("账号不存在");
        }
        //判断账号是否停用
        String status = user.getStatus();
        if (status.equals(SysConstant.XKD_STATUS_DEACTIVATE)) {
            throw new XkdException("账号已停用");
        }
        //判断账号是否已删除
        String delFlag = user.getDelFlag();
        if (delFlag.equals(SysConstant.XKD_DEL_FLAG_DELETED)) {
            throw new XkdException("账号已删除");
        }
        //补全公司信息
        Company company = new Company();
        Integer groupId = null;
        if (!user.getCompanyType().equals(SysConstant.USER_COMPANY_TYPE_ONE)) {
            company = companyService.getOne(
                    new LambdaQueryWrapper<Company>()
                            .eq(Company::getId, user.getCompanyId())
                            .select(Company::getId
                                    , Company::getCompanyName
                                    , Company::getCapitalId
                                    , Company::getAuthStatus
                                    , Company::getCompanyType
                            ));
            groupId = userGroupMapper.selectOne(new LambdaQueryWrapper<UserGroup>().eq(UserGroup::getUserId, user.getId())).getGroupId();
            if (user.getCompanyType().equals(SysConstant.USER_COMPANY_TYPE_TOW)) {
                CompanyAccount companyAccount = companyAccountMapper.selectById(user.getCompanyId());
                company.setPrestoreNo(companyAccount.getPrestoreNo());
                company.setPrestoreApplyStatus(companyAccount.getPrestoreApplyStatus());
            }
        }

        //登陆刷新权限缓存
        redisTemplate.delete("permission::" + user.getId());
        //(授权，即查询用户具有哪些权限)查询对应的用户信息
        List<SysPermission> sysPermission = iCacheService.selectSysperms(user.getId());
//        List<SysPermission> sysPermission = sysPermissionMapper.selectSysperms(user.getId(), null);
        List<String> pers = sysPermission.stream().map(SysPermission::getPerms).collect(Collectors.toList());
        SysRole role = sysRoleMapper.findRole(user.getId());
        if (role.getStatus().equals(SysConstant.XKD_STATUS_DEACTIVATE))
            throw new XkdException("角色已停用，联系管理员");
        //查询用户部门
        if (CollectionUtils.isEmpty(sysPermission))
            throw new XkdException("该用户没有任何权限页面");
        //获取数据权限
        //把数据封装成UserDetails返回
        return new LoginUser(user, pers, sysPermission, role, company, groupId);
    }
}
